import jieba
from scipy.misc import imread
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import matplotlib.pyplot as plt

def get_words(texts):
    temp={}
    word_list=[]
    word_generator = jieba.cut(texts, cut_all=False)  # 返回的是一个迭代器

    for word in word_generator:
        # if word.strip() not in str_text:
        word_list.append(word)
        temp.setdefault(word,0)
        temp[word]+=1
    print(temp)

    return ' '.join(word_list)  # 注意是空格

def word_cl():

    back_color=imread('timg.jpg')

    wc=WordCloud(background_color='white',
                 max_words=1000,
                 mask=back_color,
                 max_font_size=100,
                 random_state=42,
                 width=40000,
                 height=30000,
                 font_path='Deng.tff')
    text=get_words(read_file())
    # text = words()

    wc.generate(text)
    # 基于彩色图像生成相应彩色
    image_colors = ImageColorGenerator(back_color)
    # 显示图片
    plt.imshow(wc)
    # 关闭坐标轴
    plt.axis('off')
    # 绘制词云
    plt.figure()
    plt.imshow(wc.recolor(color_func=image_colors))
    plt.axis('off')
    # 保存图片
    wc.to_file('193th.png')

def read_file():
    with open('a.txt',encoding='utf8') as f:
        data=f.read()
    return data


if __name__ == '__main__':
    # text = get_words(read_file())
    word_cl()
